;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.BackApply", [])
        .controller("BackApplyCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "Upload", "$timeout", "EventBus", "$filter", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, UserContextService, Upload, $timeout, EventBus, $filter) {
            var btnPermissionCode = {
                backApplyAdd: window.ActionCode.backApplyAdd,
                backApplyDel: window.ActionCode.backApplyDel,
                backApplyEdit: window.ActionCode.backApplyEdit,
                backApplyExport: window.ActionCode.backApplyExport,
                backOrderInvalid: window.ActionCode.backOrderInvalid,
                backApplyFirstAudit: window.ActionCode.backApplyFirstAudit,
                backApplySecondAudit: window.ActionCode.backApplySecondAudit,
                backApplyImportAttach: window.ActionCode.backApplyImportAttach,
            };
            var sortParam = "";
            var sortFiled = {};
            var tabFlag = {
                0: "回购申请详情",
                1: "新增回购申请",
                2: "编辑回购申请"
            };

            $scope.activeFlag = [true, false, false, false, false];
            $scope.datePickerFlag = [false, false];
            $scope.tabFlag = {};
            $scope.btnPermission = {
                backApplyAdd: true,
                backApplyDel: true,
                backApplyEdit: true,
                backApplyExport: true,
                backApplyFirstAudit: true,
                backApplySecondAudit: true,
                backApplyImportAttach: true,

            };
            $scope.condition = {
                seller: true
            };
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/buyBack/export"),
                sectionParam: {ids: []},
                allUrl: ybHttp.RequestUrl("device", "/buyBack/exportAll")
            };
            $scope.orderObj = {
                headerInfo: {},
                materialList: []
            };
            $scope.tableConfig = {
                fixedWidth: 350,
                scrollWidth: 1470,
                tableCol: [
                    {
                        type: "",
                        name: "回购单号",
                        dataField: "backOrder",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortField: "back_order",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "purchaseOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "purchase_org_name",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调度员",
                        dataField: "dispatcherName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "dispatcher_name",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "总金额",
                        dataField: "totalPrice",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "total_price",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "入库单状态",
                        dataField: "sendStatusDes",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "send_status",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "入库状态",
                        dataField: "inStatusDes",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "in_status",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库单状态",
                        dataField: "createOutStatusDes",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "create_out_status",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "outStatusDes",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "out_status",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "是否作废",
                        dataField: "invalidDes",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "invalid",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "note",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "note",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核状态",
                        dataField: "statusDes",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "status",
                        sortType: ""
                    },
                    {
                        type: "attach",
                        name: "附件",
                        dataField: "attachName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        clickFn: "downloadAttach",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "第一步审核人",
                        dataField: "firstAuditName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "first_audit_name",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "第一步审核时间",
                        dataField: "firstAuditDate",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "first_audit_date",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "第一步审核意见",
                        dataField: "firstAuditNote",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortField: "first_audit_note",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "第二步审核人",
                        dataField: "secondAuditName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "second_audit_name",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "第二步审核时间",
                        dataField: "secondAuditDate",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "second_audit_date",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "第二步审核意见",
                        dataField: "secondAuditNote",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortField: "second_audit_note",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "create_name",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建时间",
                        dataField: "createDate",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortField: "create_date",
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 240,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.materielTableConfig = {
                scrollWidth: 780,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    {
                        name: "零件类型",
                        width: 150,
                        dataField: "materialsType",
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        needInput: false
                    },
                    {
                        name: "单价(￥)",
                        width: 120,
                        dataField: "price",
                        needInput: false
                    },
                    {
                        name: "数量",
                        width: 100,
                        dataField: "qty",
                        needInput: true,
                        inputType: "qty"
                    },
                    {
                        name: "总价(￥)",
                        width: 120,
                        dataField: "totalPrice",
                        needInput: false
                    },
                    {
                        name: "回购单价(￥)",
                        width: 120,
                        dataField: "backPrice",
                        needInput: true,
                        inputType: "backPrice"
                    },
                    {
                        name: "实际回购数量",
                        width: 120,
                        dataField: "backQty",
                        needInput: true,
                        inputType: "backQty"
                    },
                    {
                        name: "回购总价(￥)",
                        width: 120,
                        dataField: "backTotal",
                        needInput: false
                    },
                    {
                        name: "行内备注",
                        width: 120,
                        dataField: "backRemark",
                        needInput: false
                    }
                ]
            };

            $scope.materielExamineTableConfig = {
                scrollWidth: 780,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    {
                        name: "零件类型",
                        width: 150,
                        dataField: "materialsType",
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        needInput: false
                    },
                    {
                        name: "单价(￥)",
                        width: 120,
                        dataField: "price",
                        needInput: false
                    },
                    {
                        name: "数量",
                        width: 100,
                        dataField: "qty",
                        needInput: false,
                        inputType: "qty"
                    },
                    {
                        name: "总价(￥)",
                        width: 120,
                        dataField: "totalPrice",
                        needInput: false
                    },
                    {
                        name: "回购单价(￥)",
                        width: 120,
                        dataField: "backPrice",
                        needInput: true,
                        inputType: "backPrice"
                    },
                    {
                        name: "实际回购数量",
                        width: 120,
                        dataField: "backQty",
                        needInput: true,
                        inputType: "backQty"
                    },
                    {
                        name: "回购总价(￥)",
                        width: 120,
                        dataField: "backTotal",
                        needInput: false
                    },
                    {
                        name: "行内备注",
                        width: 120,
                        dataField: "backRemark",
                        needInput: false
                    }
                ]
            };

            $scope.viewTbConf = {
                scrollWidth: 1020,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    {
                        name: "零件类型",
                        width: 150,
                        dataField: "materialsType",
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        needInput: false
                    },
                    {
                        name: "单价(￥)",
                        width: 120,
                        dataField: "price",
                        needInput: false,
                        inputType: "price"
                    },
                    {
                        name: "数量",
                        width: 100,
                        dataField: "qty",
                        needInput: false,
                        inputType: "qty"
                    },
                    {
                        name: "总价(￥)",
                        width: 120,
                        dataField: "totalPrice",
                        needInput: false
                    },
                    {
                        name: "已建入库数量",
                        width: 120,
                        dataField: "sendQty",
                        needInput: false
                    },
                    {
                        name: "已入库数量",
                        width: 120,
                        dataField: "realQty",
                        needInput: false
                    },
                    {
                        name: "已建出库数量",
                        width: 120,
                        dataField: "createOutQty",
                        needInput: false
                    },
                    {
                        name: "已出库数量",
                        width: 120,
                        dataField: "outQty",
                        needInput: false
                    },
                    {
                        name: "回购单价(￥)",
                        width: 120,
                        dataField: "backPrice",
                        needInput: false
                    },
                    {
                        name: "实际回购数量",
                        width: 120,
                        dataField: "backQty",
                        needInput: false
                    },
                    {
                        name: "回购总价(￥)",
                        width: 120,
                        dataField: "backTotal",
                        needInput: false
                    }
                ]
            };
            $scope.sendStatusList = [
                {id: 0, name: "未申请"},
                {id: 1, name: "部分申请"},
                {id: 2, name: "已申请"}
            ];
            $scope.inStatusList = [
                {id: 0, name: "未入库"},
                {id: 1, name: "部分入库"},
                {id: 2, name: "已入库"},
                {id: 3, name: "强制结单"}
            ];
            $scope.billStateList = [
                {id: 0, name: "未审核"},
                {id: 1, name: "第一步审核拒绝"},
                {id: 2, name: "第一步审核通过"},
                {id: 3, name: "第二步审核拒绝"},
                {id: 4, name: "第二步审核通过"}
            ];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };
            $scope.submitted = false;
            $scope.dataList = [];
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        $scope.submitted = false;
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                    default:
                        break;
                }
            };

            $scope.addApply = function () {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[1];
                $scope.orderObj.headerInfo.supplierOrgName = $scope.curOrg.companyName;

                $scope.changeTab(2);
            };

            $scope.refreshData = function () {
                clearSortParam();
                getDataList(1);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.selectDispatch = function () {
                var param = {
                    name: "调度员",
                    type: 'staffByWorkspace',
                    supplierOrgId: $scope.curOrgId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.condition.dispatcherName = data.name;
                    $scope.condition.dispatcherId = data.userId;
                })
            };
            $scope.importAttach = function (item) {
                var param = {
                    name: "附件",
                    hideTemplate: true,
                    ignoreFormat: true,
                    importReqService: "device",
                    importReqUrl: "/buyBack/uploadAttach",
                    importErrorUrl: "",
                    billId: item.id
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getDataList(1);
                });
            };

            $scope.clearCondition = function () {
                $scope.condition.dispatcherName = "";

            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {seller: true};
            };

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {left: $scope.tableConfig.fixedWidth + "px"}
                };
            };

            $scope.selectDealer = function () {
                var param = {
                    name: "客户",
                    type: "dealer"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    if (!!$scope.orderObj.headerInfo.purchaseOrgId && (data.dealerOrgId !== $scope.orderObj.headerInfo.purchaseOrgId)) {
                        clearMateriel();
                    }
                    $scope.orderObj.headerInfo.purchaseOrgName = data.companyName;
                    $scope.orderObj.headerInfo.purchaseOrgId = data.platOrgId === null ? data.dealerOrgId : data.platOrgId;
                })
            };

            $scope.searchDispatch = function () {
                var param = {
                    name: "调度员",
                    type: 'staffByWorkspace',
                    supplierOrgId: $scope.curOrgId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.headerInfo.dispatcherName = data.name;
                    $scope.orderObj.headerInfo.dispatcherId = data.userId;
                })
            };

            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    if (!$scope.orderObj.headerInfo.purchaseOrgId) {
                        ybWidget.ShowToaster('error', '请选择客户');
                        return;
                    }
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.importMateriel = function () {
                if (!$scope.orderObj.headerInfo.purchaseOrgId) {
                    ybWidget.ShowToaster('error', '请选择客户');
                    return;
                }
                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/buyBack/download",
                    importReqService: "device",
                    importReqUrl: "/buyBack/import",
                    importErrorUrl: "",
                    dealerOrgId: $scope.orderObj.headerInfo.purchaseOrgId
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                    });
                    $scope.orderObj.materialList = [];
                    $scope.orderObj.materialList = angular.copy(data);
                });
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.materialList.length; i < len; i++) {
                    if (!!$scope.orderObj.materialList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.materialList.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.materialList[i].isChecked) {
                            $scope.orderObj.materialList.splice(i, 1);
                        }
                    }
                    if ($scope.orderObj.materialList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                });
            };

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.delMateriel = function (item, index) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.materialList.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialsNo);
                });
            };

            $scope.countTotal = function (item, price, qty,checkType) {
                item.priceErr = false;
                item.qtyErr = false;
                if(checkType==="checkPrice"){
                    if (!item[price] || parseFloat(item[price]) <= 0) {
                        item.priceErr = true;
                        return;
                    }
                }
                if(checkType==="checkQty"){
                    if (!item[qty] || parseFloat(item[qty]) <= 0) {
                        item.qtyErr = true;
                        return;
                    }
                }
                if (price === "price") {
                    item.totalPrice = $filter("decimalCover")(ybWidget.Times(item[qty], item[price]), 2);
                } else {
                    item.backTotal = $filter("decimalCover")(ybWidget.Times(item.backQty, item.backPrice), 2);
                }
                setTotalPrice();
            };

            // 设置价格汇总
            function setTotalPrice () {
                var total = 0;
                angular.forEach($scope.orderObj.materialList, function (item) {
                    total = $filter("decimalCover")(ybWidget.Plus(total, item.backTotal), 2);
                });
                $scope.orderObj.headerInfo.buyBackTotal = total;
            }

            $scope.saveData = function (type, invalid) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }
                var listValid = true;
                var service = "device";
                var reqUrl = "/buyBack/add";
                if ($scope.tabFlag.type === 1) {
                    reqUrl = "/buyBack/update";
                }
                if (!$scope.orderObj.materialList || $scope.orderObj.materialList.length === 0) {
                    ybWidget.ShowToaster('error', '零件不可为空');
                    return;
                }
                var param = angular.copy($scope.orderObj);
                param.headerInfo.shippingMethod = $scope.orderObj.shippingMethod;
                param.headerInfo.seller = true;

                for (var i = 0, len = $scope.orderObj.materialList.length; i < len; i++) {
                    $scope.orderObj.materialList[i].priceErr = false;
                    $scope.orderObj.materialList[i].qtyErr = false;
                    if (!$scope.orderObj.materialList[i].price || parseFloat($scope.orderObj.materialList[i].price) <= 0) {
                        $scope.orderObj.materialList[i].priceErr = true;
                        ybWidget.ShowToaster('error', '所选零件的单价不能为0');
                        listValid = false;
                        break;
                    }
                    if (!$scope.orderObj.materialList[i].qty || parseFloat($scope.orderObj.materialList[i].qty) <= 0) {
                        $scope.orderObj.materialList[i].qtyErr = true;
                        listValid = false;
                        break;
                    }
                }
                if (!listValid) {
                    return;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    if ($scope.tabFlag.type === 0) {
                        clearSortParam();
                        getDataList(1);
                    } else {
                        getDataList();
                    }
                    $scope.changeTab(0);
                });
            };

            $scope.toSort = function (config, index) {
                if (!config[index].toSort) {
                    return;
                }
                var sortType = ybWidget.ToSort(config, index);
                sortFiled = config[index];
                sortParam = sortFiled.sortField + " " + sortType;
                getDataList(1);
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    case "downloadAttach":
                        $scope.downloadAttach(item);
                        break;
                    default:
                        break;
                }
            };

            $scope.editApply = function (item) {
                $scope.tabFlag.type = 1;
                getDetail(item, 'edit');
            };

            $scope.auditApply = function (item) {
                getDetail(item, 'audit');
            };

            $scope.delApply = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/buyBack/remove";
                    var ids = [];
                    ids.push(item.id);
                    ybHttp.Post(service, reqUrl, ids).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.refreshData();
                    });
                })
            };

            $scope.invalidApply = function (item) {
                ybWidget.ShowMessage("确定要作废吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/buyBack/invalid";
                    var param = {};
                    param.id = item.id;
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.refreshData();
                    });
                })
            };

            $scope.auditPurchase = function (type, message) {
                if(type=="pass"){
                    var invalid = $scope.orderObj.materialList.every(function (item) {
                        return !!item.backPrice && (item.backPrice !== "0") && !!item.backQty && (item.backQty !== "0")
                    });

                    if (!invalid) {
                        ybWidget.ShowMessage("回购单价或实际回购数量不能为0或空", MESG_TYPE.Error);
                        return
                    }
                }
                var service = "device";
                var reqUrl = "/buyBack/audit";
                if (type === "refuse") {
                    if (!message) {
                        ybWidget.ShowMessage('请输入审核意见');
                        $scope.submitted = true;
                        return;
                    }
                    if ($scope.orderObj.headerInfo.status < 2) {
                        $scope.orderObj.headerInfo.status = 1;
                        $scope.orderObj.headerInfo.firstAuditNote = message;
                    } else {
                        $scope.orderObj.headerInfo.status = 3;
                        $scope.orderObj.headerInfo.secondAuditNote = message;
                    }
                } else {
                    if ($scope.orderObj.headerInfo.status < 2) {
                        $scope.orderObj.headerInfo.status = 2;
                        $scope.orderObj.headerInfo.firstAuditNote = message;
                    } else {
                        $scope.orderObj.headerInfo.status = 4;
                        $scope.orderObj.headerInfo.secondAuditNote = message;
                    }
                }
                $scope.orderObj.headerInfo.detailVOs = [];
                $scope.orderObj.headerInfo.detailVOs = angular.copy($scope.orderObj.materialList);

                ybHttp.Post(service, reqUrl, $scope.orderObj.headerInfo).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                    $scope.changeTab(0);
                });
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.orderObj = {
                    headerInfo: {},
                    materialList: []
                };
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMateriel = false;
            }

            function clearSortParam() {
                sortParam = "";
                if (angular.isDefined(sortFiled.sortType)) {
                    sortFiled.sortType = ""
                }
            }
            $scope.downloadAttach=function(item) {
                window.location.href = ybHttp.RequestUrl("device", "/buyBack/downloadAttach") + '?id=' + item.id;
            }
            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/buyBack/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                if (!!sortParam) {
                    param.sort = sortParam;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                param.filters.seller = true;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.firstAuditDate = $filter("YbDate")(item.firstAuditDate, 'yyyy-MM-dd HH:mm:ss');
                        item.secondAuditDate = $filter("YbDate")(item.secondAuditDate, 'yyyy-MM-dd HH:mm:ss');
                        item.createDate = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.sendStatusDes = $filter("ProgressStatus")(item.sendStatus, "returnApply");
                        item.inStatusDes = $filter("ProgressStatus")(item.inStatus, "inDepot");
                        item.createOutStatusDes = $filter("ProgressStatus")(item.createOutStatus, "returnApply");
                        item.outStatusDes = $filter("ProgressStatus")(item.outStatus, "outDepot");
                        item.statusDes = $filter("ProgressStatus")(item.status, "auditState");
                        item.invalidDes = item.invalid === 0 ? "否" : "是";
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            function clearMateriel() {
                $scope.orderObj.materialList = [];
                $scope.markInfo.allCheckedMaterial = false;
                $timeout(function () {
                    if (!$scope.orderObj.headerInfo.purchaseOrgId) {
                        EventBus.Publish("clearMaterial");
                    } else {
                        EventBus.Publish("getMaterial");
                    }
                });
            }

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            function viewDetail(item) {
                getDetail(item, 'view');
            }

            function getDetail(item, type) {
                var param = {
                    id: item.id
                };
                ybHttp.Get('device', '/buyBack/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.orderObj = resp.value;
                    $scope.tabFlag.name = tabFlag[2];
                    if (type == 'audit') {
                        if ($scope.orderObj.headerInfo.status < 3) {
                            $scope.orderObj.headerInfo.auditMessage = $scope.orderObj.headerInfo.firstAuditNote;
                        } else {
                            $scope.orderObj.headerInfo.auditMessage = $scope.orderObj.headerInfo.secondAuditNote;
                        }
                        $scope.changeTab(1);
                    }
                    if (type == 'edit') {
                        $scope.changeTab(4);
                    }
                    if (type == 'view') {
                        $scope.changeTab(3);
                    }
                });
            }

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);
